#!/usr/bin/env python
# -*-coding:utf-8-*-
# __author__="life"
import time
import os
import pickle

class PersonInfo(object):
    '''
    用户类
    '''
    BASE_DIR = os.path.dirname(os.path.abspath(__file__))
    # print(BASE_DIR)
    HOME_DIR = os.path.join(BASE_DIR,'home')
    # print(HOME_DIR)
    ConfigDir = os.path.join(BASE_DIR,'db')
    print(ConfigDir)
    def __init__(self,name,password):
        self.name = name
        self.password = password
        self.HOME_DIR = PersonInfo.BASE_DIR + '\\home\\' + self.name   # 用户家目录
        # print(self.HOME_DIR)

    def login(self):
        """
        用户登录
        :return:
        """
        dict = PersonInfo.config_read()
        if dict == None:
            return False
        if self.name in dict:
            if dict[self.name] == self.password:
                return True
        return False

    def register(self):
        """
        用户注册
        :return:
        """
        if os.path.exists(self.HOME_DIR) != True: # 实例家目录不存在
            os.system('mkdir' + ' ' + self.HOME_DIR)
        try:
            dict = PersonInfo.config_read()

            if dict == None:
                dict = {}
            if self.name not in dict.keys():
                dict[self.name] = self.password
                re = PersonInfo.config_write(dict)
                if re == True:
                    return True
            else:
                print('姓名重复')
                return False


        except Exception as e:
            print('注册异常',e)
            return False

    def view_file(self,conn):
        """
        查看用户家目录
        :param conn:
        :return:
        """
        # data = os.popen('ls' + self.HOME_DIR).read()
        data = os.listdir(self.HOME_DIR)
        # print(data)
        conn.sendall(str(data).encode())

    def Recvfile(self,conn,filename):
        """
        接收文件
        :param conn:
        :param filename:
        :return:
        """
        print('开始接收文件...')
        conn.send('Ready!'.encode())
        buffer = []
        while True:
            d = conn.recv(4096)
            if d == 'exit':
                break
            else:
                buffer.append(d)
        data = ''.join((buffer))
        if data == '':
            return False
        print(data)
        print(filename)
        print(self.HOME_DIR)
        with open(self.HOME_DIR + filename,'w') as f:
            f.write(data)
            return True

    def SendFile(self,conn,filename):
        """
        发送文件
        :param conn:
        :param filename:
        :return:
        """
        if os.path.exists(self.HOME_DIR + filename):
            print('开始发送文件...')
            conn.send('Ready!')
            time.sleep(1)
            with open(self.HOME_DIR + filename,'r') as f:
                while True:
                    data = f.read(4096)
                    print(data)
                    if not data:
                        break
                    conn.sendall(data)
            time.sleep(1)
            conn.send('exit')
            print('文件发送成功!')
        else:
            conn.send('False!')


    @staticmethod
    def config_read():
        '''
        读取配置文件
        :return:
        '''
        file_e = os.path.exists(os.path.join(PersonInfo.ConfigDir,'user_config'))
        config_file = os.path.join(PersonInfo.ConfigDir,'user_config')
        # print(config_file)
        if file_e:
            with open(config_file, 'rb') as f:
                dict = pickle.load(f)
                return dict
    @staticmethod
    def config_write(dict):
        """
        配置文件全部写入
        :param dict:
        :return:
        """
        config_file = os.path.join(PersonInfo.ConfigDir, 'user_config')
        with open(config_file, 'wb') as f:
            pickle.dump(dict, f)
            return True
